package com.huluobo.a2208mdmdemo2.myview

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.navigation.NavHostController
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.runBlocking

/**
 *  Created by LC on 2025/2/13.
 */
class MyView : View {

    private lateinit var navHostController: NavHostController
    private lateinit var paint: Paint
    private lateinit var paintText: Paint
    private var progress: Float = 0f
    private var num = 5


    constructor(context: Context, navHostController: NavHostController) : super(context) {
        this.navHostController = navHostController
        initPaint()
    }

    constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) {
        initPaint()
    }

    fun initPaint() {
        paint = Paint()
        paintText = Paint()
        paint.color = Color.RED
        paint.style = Paint.Style.STROKE
        paint.strokeWidth = 5f
        paintText.textSize = 200f
        paintText.color = Color.RED
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val rectF = RectF(100f, 100f, 600f, 600f)
        canvas.drawArc(rectF, 270f, progress, false, paint)
        canvas.drawText("$num", 300f, 420f, paintText)
    }

    fun start() {
        runBlocking {
            val animator = ValueAnimator.ofFloat(0f, 360f)
            animator.addUpdateListener {
                progress = it.animatedValue as Float
                //重绘当前view
                invalidate()
            }
            animator.interpolator = LinearInterpolator()
            animator.duration = num * 1000L
            animator.start()
        }

        runBlocking {
            val animator = ValueAnimator.ofInt(num, 0)
            animator.addUpdateListener {
                num = it.animatedValue as Int
                invalidate()
                if (num == 0) {
                    MMKV.defaultMMKV().encode("isIn", true)
                    navHostController.navigate("main")
                }
            }
            animator.interpolator = LinearInterpolator()
            animator.duration = num * 1000L
            animator.start()
        }
    }
}